package lockutil

import (
	"shop/common/log"
	"shop/dao"
	"time"
)

// TryLock 分布式锁
func TryLock(key, v string, ttlSeconds int) bool {
	return dao.GetRedisCli().SetNX(key, v, time.Duration(ttlSeconds)*time.Second).Val()
}

const releaseLockLuaScript = "if redis.call(\"get\", ARGV[1]) == ARGV[2] then return redis.call(\"del\", ARGV[1]) else return 0 end "

// ReleaseLock eg: redis里执行: eval "if redis.call(\"get\", ARGV[1]) == ARGV[2] then return redis.call(\"del\", ARGV[1]) else return 0 end " 0 key expected
func ReleaseLock(key, expected string) bool {
	log.Debugf("ReleaseLock, key=%s, v=%s", key, expected)
	res, _ := dao.GetRedisCli().Eval(releaseLockLuaScript, nil, key, expected).Int()
	return res == 1
}
